package nancal.mp.mvc.sys

import nbcp.base.comm.ApiResult
import nbcp.base.comm.JsonMap
import nbcp.base.comm.const
import nbcp.base.extend.*
import nbcp.base.utils.SpringUtil
import nbcp.mvc.sys.WriteJsonRawValue
import nbcp.web.service.upload.*
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.util.ContentCachingResponseWrapper
import java.io.InputStream
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 客户端上传流程：
 *  1. 如果需要上传，客户端调用 /sys/upload 方法，返回文件Id
 *  2. 客户端调用 业务方法，把文件Id和业务关联。
 */
@RestController
//@Import(value = arrayOf(MinioBaseService::class, AliOssBaseService::class))
class FileUploadController : BaseUploadService() {

    /**
     * 文件上传流程：
     *
     *  参数: group,storage-type
     */
    @PostMapping("/sys/upload") // ContentCachingResponseWrapper
    fun fileUpload(request: HttpServletRequest, response: HttpServletResponse) {
        super.upload(request, response, "");
        var status = response.status

        if (request.getHeader("lang") == "en") {
            (response as ContentCachingResponseWrapper).contentAsByteArray.toString(const.utf8)

            var new_string = ""
            var ori_string = response.contentInputStream.readContentString();

            if (response.contentType.contains("json")) {
                var msg = ori_string.FromJson<JsonMap>()?.get("msg").AsString()

                if (msg.hasCn()) {
                    new_string = "upload error"
                }
            } else {
                if (ori_string.hasCn()) {
                    new_string = "upload error"
                }
            }

            if (new_string.HasValue) {
                response.reset()
                response.status = status
                response.WriteJsonRawValue(new_string.ToJson())
//                response.outputStream.write(new_string.toByteArray(const.utf8))
            }
        }
    }

    override fun saveFile(
        storageType: String,
        fileStream: InputStream,
        group: String,
        fileData: UploadFileNameData
    ): ApiResult<String> {
        var storageEnum = storageType.ToEnum<StorageTypeEnum>();
        if (storageEnum == StorageTypeEnum.AliyunOss) {
            return SpringUtil.getBean<AliOssBaseService>().save(fileStream, group, fileData)
        } else if (storageEnum == StorageTypeEnum.Minio) {
            return SpringUtil.getBean<MinioBaseService>().save(fileStream, group, fileData)
        }
        return SpringUtil.getBean<LocalUploadBaseService>().save(fileStream, group, fileData)
    }

}


public enum class StorageTypeEnum {
    Local,
    AliyunOss,
    Minio
}